Kotlin 1.4 introduced functional interfaces. A functional interface is simply
a regular interface
with the fun
keyword. A functional interface is limited
to a single abstract
function, though it can have other concrete members as needed.
The value of a functional interface is that it can be implemented using
a simple lambda expression annotated with the functional interface type. We
do not need the object
keyword and a full function declaration.
In this example, we re-implement the firstOrNull()
function on Collection
as a top-level function. Where the real firstOrNull()
takes a function
type as a parameter, here we take a functional interface (Comparitizer
)
as a parameter. Consumers of our firstItemOrNull()
can provide a
Comparitizer
via a lambda expression, as we do in main()
.
The advantage over a function type is that you could have your functional interface implement other concrete functions, if desired.